<?php
/**
 * Created by PhpStorm.
 * User: xuho
 * Date: 2020-05-04
 * Time: 00:34
 */

namespace app\common\subscribe;


use app\common\model\mysql\cdc\AccountModel;
use app\common\model\mysql\cdc\UserModel;
use app\common\model\mysql\cdc\UserRelationModel;
use app\common\service\PasswordService;

class MerchantSubscribe
{
    public function onCreate($request)
    {

    }

    /**
     * 添加商户关联账号
     * @param $param
     */
    protected function merchantAccount($param)
    {
        $accountId = AccountModel::getAlone(['mobile' => $param['mobile']]);

        // 添加账号
        if (empty($accountId)) {
            $inputData = [
                'account_name' => $param['mobile'],
                'password' => PasswordService::account(),
                'realname' => $param['realname'],
                'mobile' => $param['mobile'],
                'system_ids' => in_array(0, $param['system_ids']) ? 0 : implode(',', $param['system_ids']),
                'group_ids' => in_array(1, $param['group_ids']) ? 1 : implode(',', $param['group_ids']),
            ];
            AccountModel::addData($inputData);
        } else {
            $inputData = [
                'system_ids' => in_array(0, $param['system_ids']) ? 0 : implode(',', $param['system_ids']),
                'group_ids' => in_array(1, $param['group_ids']) ? 1 : implode(',', $param['group_ids']),
            ];
            AccountModel::editData($inputData, ['id' => $accountId]);
        }
    }

    /**
     * 添加商户关联用户
     * @param $mobile
     * @param $merchantId
     */
    protected function merchantUser($mobile, $merchantId)
    {
        // 如果不存在用户，则创建用户
        $userId = UserModel::getAlone(['mobile' => $mobile]);
        if (empty($userId)) {
            $user = UserModel::addData(['mobile' => $mobile]);
            $userId = $user->id;
        }

        if (!UserRelationModel::checkRowExists(['user_id' => $userId, ['merchant_id' => $merchantId]])) {
            UserRelationModel::addData(['user_id' => $userId, 'merchant_id' => $merchantId]);
        }
    }
}